package com.sky.wsp.spel.aop;

import cn.hutool.core.util.StrUtil;
import com.sky.wsp.spel.annotation.SysLog;
import com.sky.wsp.spel.utils.SpelUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.EvaluationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class SysLogAspect {

    @Pointcut("@annotation(com.sky.wsp.spel.annotation.SysLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //执行方法
        Object result = point.proceed();

        //保存日志
        saveSysLog(point, result);
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, Object result) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog syslog = method.getAnnotation(SysLog.class);
        if (syslog != null) {
            EvaluationContext context = SpelUtil.getContext(joinPoint, result);
            //注解上的描述
            if (StrUtil.isNotBlank(syslog.tenantId())) {
                String spelValue = SpelUtil.parseSpEL(syslog.tenantId(), context);
                System.out.println("注解tenantId SpEL:" + spelValue);
            }//注解上的描述
            if (StrUtil.isNotBlank(syslog.userId())) {
                String spelValue = SpelUtil.parseSpEL(syslog.userId(), context);
                System.out.println("注解userId SpEL:" + spelValue);
            }
        }
    }
}